package com.ruoyi.base.utils.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码工具类
 *
 * @author lcf
 */
public class BarCodeUtils {
    /**
     * 条形码宽度
     */
    private static final int WIDTH = 300;
    /**
     * 条形码高度
     */
    private static final int HEIGHT = 70;

    /**
     * 字体大小
     */
    private static final int FONT_SIZE = 28;

    /**
     * 加文字 条形码
     */
    private static final int WORD_HEIGHT = HEIGHT + FONT_SIZE;

    /**
     * 生成条形码
     */
    public static String getBase64BarCode(String content) {
        //配置条码参数
        Map<EncodeHintType,Object> hints = new HashMap<>(3);
        //设置条码两边空白边距为0，默认为10，如果宽度不是条码自动生成宽度的倍数则MARGIN无效
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        Code128Writer code128Writer = new Code128Writer();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            BitMatrix bitMatrix = code128Writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);

            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            bufferedImage = insertWords(bufferedImage, content);
            if (bufferedImage == null) {
                throw new RuntimeException("生成条形码失败");
            }

            ImageIO.write(bufferedImage, "jpg", outputStream);

            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("生成条形码失败", e);
        }
    }

    private static BufferedImage insertWords(BufferedImage image, String words) {
        // 新的图片，把带logo的二维码下面加上文字
        if (!StringUtils.isEmpty(words)) {
            BufferedImage outImage = new BufferedImage(WIDTH, WORD_HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            g2d.setColor(Color.BLACK);
            // 字体、字型、字号
            g2d.setFont(new Font("黑体", Font.PLAIN, FONT_SIZE));
            int wordStartY = HEIGHT + 21;
            int inputWidth = new Code128Writer().encode(words).length;
            int fullWidth = inputWidth + 1;
            int outputWidth = Math.max(WIDTH, fullWidth);
            int multiple = outputWidth / fullWidth;
            int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
            int x = leftPadding;
            String[] split = words.split("");
            int step = new Long(Math.round(WIDTH - leftPadding * 2) / words.length()).intValue();
            for (String s : split) {
                g2d.drawString(s, x, wordStartY);
                x = x + step;
            }
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性 （抗锯齿）
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        // 填充整个屏幕
        g2d.fillRect(0, 0, 600, 600);
        // 设置笔刷
        g2d.setColor(Color.BLACK);
    }
}
